// pages/music-player/index.js
const db = wx.cloud.database()
import {audioContext , playerStore ,userStore} from '../../store/index'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
const playModeNames = ["order","repeat","random"]
Page({

  data: {
    id: 0,
    nickname:"",
    username:"",
    avatarUrl:"",
    currentSong:{},
    lyricInfos:[],
    durationTime:0,
    isLogin:"false",

    currentTime:0,
    currentLyricIndex: 0,
    currentLyricText:"",

    isPlaying:false,
    playingName:"pause",

    playModeIndex:0,
    playModeName:"order",

    currentPage:0,
    contentHeight:0,
    sliderValue: 0,
    isSliderChanging: false,
    lyricScrollTop: 0,

    songId: 0,
    show: false,
    haveComment:"",
    haveCollection:"",
    commentId:"",
    commentShow: false,
    collectionShow:false,
    addCollectionShow:false,
    commentList:[],
    collectionList:[],
    canPlaySongList: [],
    canPlaySongCurrentIndex: 0,
    commentValue:"",
    addCollectionValue:"",
    songDetail: [],

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
 //获取传入的id
    const id = options.id
    this.setData({ id ,songId:id })

    // playerStore.dispatch("playMusicWithSongIdAction", { id })

    //根据id获取歌曲信息
    this.setupPlayerStoreListener()

    // 动态计算内容高度
    const globalData = getApp().globalData
    const screenHeight = globalData.screenHeight
    const statusBarHeight = globalData.statusBarHeight
    const navBarHeight = globalData.navBarHeight
    const contentHeight = screenHeight - statusBarHeight - navBarHeight
    this.setData({ contentHeight })

    playerStore.onState("playListSongs", (res) => {
      this.setData({
        canPlaySongList: res
      })
    })

    playerStore.onState("playListIndex", (res) => {
      this.setData({
        canPlaySongCurrentIndex: res
      })
    })
  },


  //点击歌曲/歌词
  handleSongClick:function(){
    this.setData({ currentPage : 0 })
  },

  handleLyricClick:function(){
    this.setData({ currentPage : 1 })
  },

  //滑动swiper
  handleSwiperChange:function(event){
    const current = event.detail.current
    this.setData({ currentPage: current })
  },
//根据id获取歌曲信息
  setupPlayerStoreListener:function(){
    playerStore.onStates(["currentSong","durationTime","lyricInfos"],({
      currentSong,
      durationTime,
      lyricInfos,
    })=>{
      if(currentSong)this.setData({currentSong})
      if(durationTime)this.setData({durationTime})
      if(lyricInfos)this.setData({lyricInfos})
    })

    // 监听currentTime/currentLyricIndex/currentLyricText
    playerStore.onStates(["currentTime","currentLyricIndex","currentLyricText"],({
      currentTime,
      currentLyricIndex,
      currentLyricText
    })=>{
      //时间变化
      if(currentTime && !this.data.isSliderChanging){
        const sliderValue = currentTime / this.data.durationTime * 100
        this.setData({currentTime , sliderValue })
      }
      //歌词变化
      if(currentLyricIndex){
        this.setData({currentLyricIndex,lyricScrollTop:currentLyricIndex * 35})
      }
      if(currentLyricText) this.setData({currentLyricText})
    })

    //监听播放模式相关的数据
    playerStore.onStates(["playModeIndex","isPlaying"],({playModeIndex, isPlaying})=>{
      if(playModeIndex !== undefined){
        this.setData({
          playModeIndex,
          playModeName:playModeNames[playModeIndex]})
      }
      if(isPlaying !== undefined){
        this.setData({
          isPlaying,
          playingName :isPlaying? "pause" : "resume"
         })
      }
    })
  },
  handleSliderChanging:function(event){
    const value = event.detail.value
    const currentTime = this.data.durationTime * value / 100
    this.setData({ isSliderChanging:true , currentTime: currentTime})
  },

  handleSliderChange:function(event){
    //获取slider变化的值
    const value = event.detail.value

    //需要播放的currentTime
    const currentTime = this.data.durationTime * value / 100

    //设置context播放currentTime位置的音乐
    // audioContext.pause()
    audioContext.seek(currentTime / 1000)

    //记录最新的sliderValue
    this.setData({ sliderValue: value ,isSliderChanging: false})

  },

  handleBackBtnClick:function(){
    wx.navigateBack()
  },

//==========================点击评论===========================
  handleCommentBtnClick:function(){
    this.setData({commentList:[]})
    playerStore.onState("songId",(value)=>{
        this.setData({songId:value*1})
      })
    var that = this
    this.setData({ commentShow:true })
    db.collection('comment').where({
      songId:this.data.songId * 1
    })
    .get().then(res =>{
     
      if(res.data.length == 0){
        this.setData({haveComment:false})
        return
      }else if(res.data[0].comment){
        console.log(res);
        this.setData({commentList:res.data[0].comment})
        this.setData({haveComment:true})
        this.setData({commentId:res.data[0]._id})
      }
      
    })

  },

//===========================点击收藏===========================
  handleCollectionBtnClick:function(){
    this.handleToLoginClick()
    playerStore.onState("songId",(value)=>{
      this.setData({songId:value*1})
    })
    userStore.onState("username",(value)=>{
      this.setData({username:value})
    })
    this.setData({ collectionShow : true})
    
    //是否有歌单
    db.collection('collectionMenu').where({
      userName:this.data.username
    }).get().then(res =>{
      if(res.data.length == 0 && this.data.isLogin =='true' ){
        this.setData({haveCollection:false})
      }
      else if(res.data.length != 0 && this.data.isLogin == 'true'){
          this.setData({collectionList:res.data})
          this.setData({haveCollection:true})
      }
      // console.log(res.data[0].collectionList)
      // this.setData({ collectionList:res.data[0].collectionList })
    })

  },

//===========================点击新建歌单========================
  handleNewCollectionClick:function(){
    this.setData({addCollectionShow:true})
  },

//=============================关闭新建歌单======================
  onAddCollectionClose:function(){
    this.setData({addCollectionShow:false})
  },

//==============================输入歌单名======================
  onChangeCollection:function(event){
    this.setData({addCollectionValue:event.detail})
  },
//=========================点击确认新建歌单按钮================
  handleAddCollectionBtnClick:function(){
    console.log(this.data.addCollectionValue);
      if(this.data.addCollectionValue == ''){
        Dialog.alert({
          title:'请输入歌单名',  
          message: '请输入歌单名',
        })       
      }
      else if(this.data.addCollectionValue !== ''){
        db.collection('collectionMenu').add({
          data:{
            
            // id:this.data.currentSong[0].id,
            
            coverImgUrl:this.data.currentSong[0].al.picUrl,
            name:this.data.addCollectionValue,
            userName:this.data.username,
            collectionList:{
              ListName:this.data.addCollectionValue,
              songInfo:[{
                al:[{
                  picUrl:this.data.currentSong[0].al.picUrl,
                }],
                ar:[{name:this.data.currentSong[0].ar[0].name}],
                id:this.data.currentSong[0].id * 1,              
                name:this.data.currentSong[0].name
              }]
            }
          }
        })
        .then(res=>{
          this.setData({addCollectionValue:''})
          this.setData({addCollectionShow:false})
          Toast('创建成功');
          this.handleCollectionBtnClick()
        })
      }
      
      
  },

//==========================点击已经存在的歌单加歌曲==================
  handleAddSongToCollectionBtnClick:function(event){
    const index = event.currentTarget.dataset.index
    console.log(this.data.collectionList[index]);
    const collectionId = this.data.collectionList[index]._id
    const collectionList = this.data.collectionList[index].collectionList
    var canCollect = true
    playerStore.onState("songId",(value)=>{
      this.setData({songId:value*1})
    })
    for(let i = 0;i < collectionList.songInfo.length; i++){
      if(this.data.songId == collectionList.songInfo[i].id)
      {
        Toast('该歌单歌曲已存在');
        canCollect = false
      }
    }
    if(canCollect){
      Dialog.confirm({
        title:'标题',
        message: '是否要收藏到此歌单？',
      })
      .then(() => {
        const _ = db.command
        db.collection('collectionMenu').doc(collectionId).update({
          data:{
            collectionList:{
              songInfo: _.push({
                al:[{
                  picUrl:this.data.currentSong[0].al.picUrl,
                }],
                ar:[{name:this.data.currentSong[0].ar[0].name}],
                id:this.data.currentSong[0].id * 1,              
                name:this.data.currentSong[0].name
              })
            }
          }
        }).then(res=>{
          Toast('收藏成功');
          this.handleCollectionBtnClick()
        })
        
      })
      
    }
    
  },

  onCommentClose:function(){
    this.setData({ commentShow:false })
  },

  //=======================关闭收藏========================
  onCollectionClose:function(){
    this.setData({ collectionShow:false })
  },

  // =======================填写评论赋值==========================
  onChangeComment:function(event){
    console.log(event.detail)
    this.setData({commentValue:event.detail})
  },
  // =======================点击评论框没有登陆则跳转==========================
  handleToLoginClick:function(){
    userStore.onState("isLogin",(value)=>{
      console.log(value)
      this.setData({isLogin:value})
    })
    if(this.data.isLogin == "false"){
      Dialog.confirm({
        title:'标题',
        message: '您还未登录，是否前往登录？',
      })
        .then(() => {
          wx.navigateTo({
            url: '../login/index',
          })
        })
        .catch(() => {
          console.log('取消')
        });
    }
  },

  //=======================点击发表按钮===============================
  handleMakeCommentBtnClick:function(){
    const comment = this.data.commentValue
    if(!comment){
      Dialog.alert({
        title:"评论不能为空",
        message:"评论不能为空"
      })
      return;
    }
    userStore.onState("nickname",(value)=>{
      console.log(value)
      this.setData({nickname:value})
    })
    userStore.onState("avatarUrl",(value)=>{
      console.log(value)
      this.setData({avatarUrl:value})
    })
    //本来歌曲没有评论的
    if(this.data.haveComment == false){
      db.collection('comment').add({
        data:{
          songId:this.data.songId * 1,
          comment:[{
            content:comment,
            userName:this.data.nickname,
            userPic:this.data.avatarUrl
          }]
        }
      }).then(res=>{
        Toast('发表成功');
        this.handleCommentBtnClick()
        this.setData({commentValue:""})
      })
      
    }
    //本来歌曲有评论的
    if(this.data.haveComment == true){
      const _ = db.command
      db.collection('comment').doc(this.data.commentId).update({
        data:{
          comment: _.push({
            content:comment,
            userName:this.data.nickname,
            userPic:this.data.avatarUrl
          })
        }
      })
      .then(res=>{
        Toast('发表成功');
        this.handleCommentBtnClick()
        this.setData({commentValue:""})
      })
      
    }
    
    
  },

  handleModeBtnClick:function(){
    let playModeIndex = this.data.playModeIndex + 1
    if(playModeIndex === 3) playModeIndex = 0

    playerStore.setState("playModeIndex",playModeIndex)
  },

  handlePlayBtnClick:function(){
    playerStore.dispatch("changeMusicPlayStatusAction",!this.data.isPlaying)
  },

  handlePrevBtnClick:function(){
    playerStore.dispatch("changeNewMusicAction", false)
  },
  
  handleNextBtnClick:function(){
    playerStore.dispatch("changeNewMusicAction")
  },

  handleSelectBtnClick: function (event) {
    const index = event.currentTarget.dataset.index
    playerStore.dispatch("selectNewMusicAction", index)
  },

  //==============================打开歌曲目录===============================
  onClickShow() {
    this.setData({
      show: true
    });
  },

  onClickHide() {
    this.setData({
      show: false
    });
  },

  onShow:function(){
    userStore.onState("isLogin",(value)=>{
      this.setData({isLogin:value})
    })
    // userStore.onState("id",(value)=>{
    //   this.setData({id:value * 1})
    // })
  }
})